//
//  DefaultTools.m
//  GGInternbird
//
//  Created by iOSer on 16/6/3.
//  Copyright © 2016年 耿文康. All rights reserved.
//

#import "DefaultTools.h"

//首页时间戳
#define bannerTimePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"fpbannerTime.plist"]
//热搜词
#define hotSearchTimePath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"hotSearchTime.plist"]
//求职消息
#define jobMsgPath [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"MsgCache.plist"]

#define jobHeadURL APIDEBUG?@"http://test.m.internbird.com":@"http://m.internbird.com"
#define companyHeadURL APIDEBUG?@"http://test.m.internbird.com":@"http://m.internbird.com"

#define bannerArrayPath @"fpbannerList.data"
#define hotSearchArray @"HotSearchArray.data"
@interface DefaultTools(){
    int point;
    BOOL appStart;
}
@end
@implementation DefaultTools


static DefaultTools *  defaultTools = nil;

+ (DefaultTools *)sharedInstance{
    static dispatch_once_t once;
    dispatch_once(&once, ^(){
        defaultTools = [[DefaultTools alloc] init];
    });
    return defaultTools;
}
/**
 *  本地化存储系列
 *
 */

/**
 *  推送消息处理
 *  @name:jobMsg quickMsg visitMsg systemMsg
 */
-(NSDictionary *)pushMsgRead{
    NSDictionary *dic = [NSKeyedUnarchiver unarchiveObjectWithFile:jobMsgPath];
    return dic;
}
//清理消息
-(void)pushMsgClearWithName:(NSString *)name{
    
    NSDictionary *dic = [NSDictionary dictionary];
    NSDictionary *job = [NSDictionary dictionary];
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:jobMsgPath]) {
        
        dic = [NSKeyedUnarchiver unarchiveObjectWithFile:jobMsgPath];
        
    }
    
    job = @{
            @"pointNum":[NSNumber numberWithBool:NO],
            @"msg":@"暂无最新消息",
            @"time":[NSNumber numberWithInt:0]
            };
    
    NSMutableDictionary *dicM = [[NSMutableDictionary alloc] initWithDictionary:dic];
    [dicM setObject:job forKey:name];
    [NSKeyedArchiver archiveRootObject:(NSDictionary *)dicM toFile:jobMsgPath];
    
}
//添加消息
-(void)pushMsgPointAddMsg:(NSString *)msg andTime:(NSNumber *)time andName:(NSString *)name{
    
    NSDictionary *job = [NSDictionary dictionary];
    
    NSDictionary *dic = [NSDictionary dictionary];
    if ([NSKeyedUnarchiver unarchiveObjectWithFile:jobMsgPath]) {
        
        dic = [NSKeyedUnarchiver unarchiveObjectWithFile:jobMsgPath];
        
    }
    
    job = @{
            @"pointNum":[NSNumber numberWithBool:YES],
            @"msg":msg,
            @"time":time
            };
    
    NSMutableDictionary *dicM = [[NSMutableDictionary alloc] initWithDictionary:dic];
    [dicM setObject:job forKey:name];
    
    [NSKeyedArchiver archiveRootObject:(NSDictionary *)dicM toFile: jobMsgPath];
}

//是否第一次启动
-(BOOL)isAppFirstStart{
    return appStart;
}
-(void)appFirstStartWith:(BOOL)boo{
    appStart = boo;
}
//热门搜索
-(void)dataStoreTimeWithHotSearch{
    [self writeTimeWithPath:hotSearchTimePath];
}
-(BOOL)hotSearchDataStore{
    return [self dataStoreTimeWithPath:hotSearchTimePath];
}
-(void)dataWriteWithHotSearchArray:(NSArray *)HotSearchArray{
    [self writeToFieldWithDataName:hotSearchArray andArray:HotSearchArray];
}
-(NSArray *)dataReadWithHotSearch{
    return [self readFieldToPathWithName:hotSearchArray];
}

//首页bannner
-(void)dataStoreTimeWithFPBanner{
    [self writeTimeWithPath:bannerTimePath];
}
-(BOOL)fpBannerDataStore{
    return [self dataStoreTimeWithPath:bannerTimePath];
}

-(void)dataWriteWithFPBanner:(NSArray *)fpBannerArray{
    [self writeToFieldWithDataName:bannerArrayPath andArray:fpBannerArray];
}
-(NSArray *)dataReadWithFPBanner{
    
    return [self readFieldToPathWithName:bannerArrayPath];
}
//对象解档
-(NSArray *)readFieldToPathWithName:(NSString *)name{
    // 1.获得Documents的全路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:name];
    
    // 3.从文件中读取MJStudent对象
    NSArray *stu = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    
    return stu;
}
//对象归档
-(void)writeToFieldWithDataName:(NSString *)dataName andArray:(NSArray *)array{
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    // 2.2.获得文件的全路径
    NSString *path = [doc stringByAppendingPathComponent:dataName];
    // 2.3.将对象归档
    [NSKeyedArchiver archiveRootObject:array toFile:path];
}
//存储加载时时间戳
-(void)writeTimeWithPath:(NSString *)path{
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    [NSKeyedArchiver archiveRootObject:localeDate toFile: path];
}
-(BOOL)dataStoreTimeWithPath:(NSString *)path{
    NSDate *date1 = [NSKeyedUnarchiver unarchiveObjectWithFile:path];
    //首先创建格式化对象
    
    NSDate *date = [NSDate date];
    NSTimeZone *zone = [NSTimeZone systemTimeZone];
    NSInteger interval = [zone secondsFromGMTForDate: date];
    NSDate *localeDate = [date  dateByAddingTimeInterval: interval];
    //计算时间间隔（单位是秒）
    
    NSTimeInterval time = [localeDate timeIntervalSinceDate:date1];
    
    //计算天数、时、分、秒
    
    int hours = ((int)time)%(3600*24)/3600;
    
    BOOL res;
    if (date1) {
        if (hours > 2) {
            res = YES;
        }else{
            res = NO;
        }
    }else{
        res = YES;
    }
    
    return res;
}
//时间戳转换
-(NSString *)timeSwitchString:(double)time andDateFomat:(NSString *)dateFormat{
    NSTimeInterval timeInterval = time/1000;
    NSDate *confromTimesp = [NSDate dateWithTimeIntervalSince1970:timeInterval];
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:dateFormat]; //用来设置NSDate的输出格式
    
    NSString *setTime=[formatter stringFromDate:confromTimesp];
    
    return setTime;
}


//获取当前控制器
-(UIViewController *)getCurrentVC{
    UIViewController *result = nil;
    UIWindow *window = [[UIApplication sharedApplication] keyWindow];
    if (window.windowLevel != UIWindowLevelNormal) {
        NSArray *windows = [[UIApplication sharedApplication] windows];
        for (UIWindow *tmpWin in windows) {
            if (tmpWin.windowLevel == UIWindowLevelNormal) {
                window = tmpWin;
                break;
            }
        }
    }
    
    UIView *frontView = [[window subviews] objectAtIndex:0];
    id nextResponder = [frontView nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        result = nextResponder;
    }else{
        result = window.rootViewController;
    }
    
    
    return result;
}
-(CALayer *)baseLayerMake{
    CALayer *layer = [[CALayer alloc] init];
    layer.cornerRadius = 5;
    layer.shadowColor = [UIColor blackColor].CGColor;//shadowColor阴影颜色
    layer.shadowOffset = CGSizeMake(0,1.5);//shadowOffset阴影偏移,x向右偏移4，y向下偏移4，默认(0, -3),这个跟shadowRadius配合使用
    layer.shadowOpacity = 0.1;//阴影透明度，默认0
    layer.shadowRadius = 5;//阴影半径，默认3
    return layer;
}
//电话正则
- (BOOL)validatePhoneNumber:(NSString *) textString
{
    NSString* number=@"0?(13|14|15|17|18)[0-9]{9}";
    NSPredicate *numberPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",number];
    return [numberPre evaluateWithObject:textString];
}
//密码正则
- (BOOL)validatePass:(NSString *) textString
{
    NSString* pass=@"^[\\@A-Za-z0-9\\!\\#\\$\%\\^\\&\\*\\.\\~]{6,22}$";
    NSPredicate *passPre = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",pass];
    return [passPre evaluateWithObject:textString];
}
-(void)stringMake{
    NSString *string =@"sdfsfsfsAdfsdf";
    
    NSRange range = [string rangeOfString:@"f"];//匹配得到的下标
    
    NSLog(@"rang:%@",NSStringFromRange(range));
    
    string = [string substringWithRange:range];//截取范围类的字符串
    
    NSLog(@"截取的值为：%@",string);
}

-(NSString *)nowDateWithTime{

    NSDate *nowDate = [NSDate date];
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    
    [formatter setDateFormat:@"MM月dd日"]; //用来设置NSDate的输出格式
    
    NSString *setTime=[formatter stringFromDate:nowDate];
    
    return setTime;
}

#pragma mark - 加班时间计算
/*   -(void)workPlusTimeWithString:(NSString *)string  算加班时间
 *   -(int)compareDate:(NSString*)date01 withDate:(NSString*)date02；比较date大小
 *   -(NSDate *)timeSwitchString:(NSString *)string 字符串转NSDate
 **/
-(void)workPlusTimeWithString:(NSString *)string{
    int plusWorkTime = 0;
    NSString *workTime = string;
    
    NSArray *workTimeArray = [workTime componentsSeparatedByString:@" "];
    
    NSMutableArray *workTimeArrayM = [NSMutableArray new];
    for (NSString *dayWorkTime in workTimeArray) {
        NSArray *dayWorkTimeA = [dayWorkTime componentsSeparatedByString:@","];
        [workTimeArrayM addObject:dayWorkTimeA];
    }
    for (int i = 0; i<workTimeArrayM.count; ++i) {
        NSArray *array = workTimeArrayM[i];
        NSString *string = array[0];
        NSString *defaultTime = @"09:00";
        int a = [self compareDate:defaultTime withDate:string];
        if (a<0) {
            NSArray *arraya = @[defaultTime,array[1]];
            [workTimeArrayM replaceObjectAtIndex:i withObject:arraya];
        }
        
    }

    for (int i = 0; i<workTimeArrayM.count; ++i) {
        NSArray *workArray = workTimeArrayM[i];
        NSString *topTime = workArray[0];
        NSString *bommonTime = workArray[1];
        NSDate *date1 = [self timeSwitchString:topTime];
        NSDate *date = [self timeSwitchString:bommonTime];
        NSTimeInterval time = [date timeIntervalSinceDate:date1];
        int hours = ((int)time)%(3600*24)/3600;
        int hoursWithMinutes = hours*60;
        int minutes = ((int)time)%(3600*24)%3600/60;
        int dayAllWorkTime = hoursWithMinutes + minutes;
        int dayAllPlusWorkTime = dayAllWorkTime - 570;
        if (dayAllPlusWorkTime<60 && dayAllPlusWorkTime>0) {
            dayAllPlusWorkTime = 0;
        }
        plusWorkTime = plusWorkTime + dayAllPlusWorkTime;
    }
    double allTime = plusWorkTime/60;
    NSLog(@"%f",allTime);
    
}

-(int)compareDate:(NSString*)date01 withDate:(NSString*)date02{
    int ci;
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    [df setDateFormat:@"HH:mm"];
    NSDate *dt1 = [[NSDate alloc] init];
    NSDate *dt2 = [[NSDate alloc] init];
    dt1 = [df dateFromString:date01];
    dt2 = [df dateFromString:date02];
    NSComparisonResult result = [dt1 compare:dt2];
    switch (result)
    {
            //date02比date01大
        case NSOrderedAscending: ci=1; break;
            //date02比date01小
        case NSOrderedDescending: ci=-1; break;
            //date02=date01
        case NSOrderedSame: ci=0; break;
        default: NSLog(@"erorr dates %@, %@", dt2, dt1); break;
    }
    return ci;
}

//时间戳转换
-(NSDate *)timeSwitchString:(NSString *)string{
    
    
    NSDateFormatter *formatter=[[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"HH:mm"]; //用来设置NSDate的输出格式
    NSDate *aaaa = [formatter dateFromString:string];
    //    NSTimeInterval time = [aaaa timeIntervalSince1970];
    return aaaa;
}


-(UIImage *)imageMakeWithRect:(CGRect)rect Color:(UIColor *)color{
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, color.CGColor);
    CGContextFillRect(context, rect);
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return img;
}


@end







#import "SVProgressHUD.h"
@interface GGShowHUDTool(){
    NSURL *shardUrl;
    NSString *shardString;
}
@end


@implementation GGShowHUDTool

static GGShowHUDTool *  showHUDTool = nil;
+ (GGShowHUDTool *)sharedInstance{
    static dispatch_once_t once;
    dispatch_once(&once, ^(){
        showHUDTool = [[GGShowHUDTool alloc] init];
    });
    return showHUDTool;
}
-(void)setBgColor{
//    [SVProgressHUD setRingThickness:5];
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleCustom];
    [SVProgressHUD setDefaultMaskType:SVProgressHUDMaskTypeNone];
    [SVProgressHUD setBackgroundColor: HEXColor(0x000000, 1)];
    [SVProgressHUD setForegroundColor: HEXColor(0xffffff, 1)];
   
}
-(void)showGetHud:(NSString *)str withTime:(NSTimeInterval)time{
//    [self setBgColor];
    [SVProgressHUD showWithStatus:str];
    
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:time];
}
-(void)showInfoHudWith:(NSString *)str{
    
    [self setBgColor];
    [SVProgressHUD showInfoWithStatus:str];
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:2];
}
//success
-(void)showYesHudWith:(NSString *)str{
    [self setBgColor];
    [SVProgressHUD showSuccessWithStatus:str];
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
    
    //    [SVProgressHUD dismiss];
}

-(void)showImage:(UIImage *)image andString:(NSString *)string{
    [SVProgressHUD showImage:image status:string];
}
//error
-(void)showNoHudWith:(NSString *)str{
    [self setBgColor];
    
    [SVProgressHUD showErrorWithStatus:str];
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:1];
};

-(void)showGetHud:(NSString *)str{
    [self setBgColor];
    [SVProgressHUD showWithStatus:str];
    [self performSelector:@selector(dismiss) withObject:nil afterDelay:2];
//    [SVProgressHUD showWithStatus:str];
}
-(void)dismiss{
    [SVProgressHUD dismiss];
}
@end
 
